export default {
  namespaced: true,
  state: {
    taskList: [],
    taskDetail: {},
  },
  mutations: {
    setTaskList(state, value) {
      state.taskList = [...state.taskList, ...value];
    },
    setTaskDetail(state, value) {
      state.taskDetail = value;
    },
    clearTaskList(state) {
      state.taskList = [];
    },
  },
  actions: {
    // 获取任务列表
    getTaskList({ commit }, payload) {
      const db = wx.cloud.database(),
        { page, limitCount, userId, type } = payload;
      return new Promise(async (resolve, reject) => {
        try {
          let newList = [];
          // 分配给我的
          if (type) {
            // 自己创建的分配列表
            const taskList = await db
              .collection("taskList")
              .where({ _openid: userId, isMe: false, isTeam: false })
              .skip(page * limitCount)
              .limit(limitCount)
              .get();
            newList = [...taskList.data];
          } else {
            const meTask = await db
              .collection("taskList")
              .where({ _openid: userId, isMe: true })
              .get();
            // 队伍的任务列表
            const teamTaskList = await db
              .collection("taskList")
              .where({ _openid: userId, isTeam: true })
              .get();
            const taskList = await db
              .collection("taskList")
              .where({ _openid: userId, isMe: false, isTeam: false })
              .skip(page * limitCount)
              .limit(limitCount)
              .get();
            newList = [...meTask.data, ...teamTaskList.data, ...taskList.data];
          }

          console.log("列表数据：", newList);
          commit("setTaskList", newList);
          resolve("获取列表成功");
        } catch (err) {
          console.log("获取任务列表失败：", err);
          reject(err);
        }
      });
    },

    // 获取任务详情
    getTaskDetail({ dispatch }, payload) {
      const db = wx.cloud.database(),
        _ = db.command,
        { taskId } = payload;

      return new Promise(async (resolve, reject) => {
        try {
          const res = await db.collection("task").where({ _id: taskId }).get();
          // 如果获取到的内容为空，那么一定是获取的分配任务且已经被原任务作者删除，因此也要删除原用户的任务
          const item = res.data[0];
          if (!item) {
            await dispatch("deleteTask", payload);
            resolve({});
          } else {
            const timeNow = new Date().getTime();
            if (timeNow >= new Date(item.endTime).getTime() && !item.isTime) {
              item.isTime = true;
              dispatch("changeTaskStatus", item._id);
            }
            resolve(item);
          }
        } catch (err) {
          console.log("获取任务详情失败：", err);
          reject(err);
        }
      });
    },

    // 添加我的队伍任务
    addTeamTaskList({}, payload) {
      const db = wx.cloud.database(),
        _ = db.command,
        { userId, teamTaskContent, teamId } = payload;
      teamTaskContent.teamId = teamId; // 必须保存teamid字段（来查询队友）
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db
            .collection("taskList")
            .add({ data: teamTaskContent });
          const taskListId = res._id;
          await db
            .collection("user")
            .where({ _openid: userId })
            .update({
              data: {
                teamTaskList: _.push(taskListId),
              },
            });
          resolve("添加我的队伍任务成功");
        } catch (err) {
          console.log("添加我的队伍任务失败：", err);
          reject(err);
        }
      });
    },

    // 添加分享任务
    addTaskByallocCode({}, payload) {
      const db = wx.cloud.database(),
        _ = db.command,
        { listId, allocCode } = payload;
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db.collection("task").where({ allocCode }).get();
          // 判断输入的分享码是否对应到任务
          if (res.data.length) {
            const taskId = res.data[0]._id;
            await db
              .collection("taskList")
              .where({ _id: listId })
              .update({
                data: {
                  tasks: _.push(taskId),
                },
              });
            resolve("success");
          } else {
            resolve("empty");
          }
        } catch (err) {
          console.log("添加分享任务失败：", err);
          reject(err);
        }
      });
    },
    // 创建任务列表
    addTaskList({ dispatch }, payload) {
      const db = wx.cloud.database(),
        { listContent } = payload;
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db.collection("taskList").add({
            data: listContent,
          });
          await dispatch("addTaskToUser", res._id, { root: true });
          await dispatch("getUserInfo", { type: 0 }, { root: true });
          resolve("创建列表成功");
        } catch (err) {
          console.log("创建任务列表失败：", err);
          reject(err);
        }
      });
    },
    // 向列表中添加任务
    addTask({}, payload) {
      const db = wx.cloud.database(),
        _ = db.command,
        { listId, taskContent, isAlloc, taskId } = payload;

      return new Promise(async (resolve, reject) => {
        try {
          if (!isAlloc) {
            const res = await db.collection("task").add({
              data: taskContent,
            });
            await db
              .collection("taskList")
              .where({ _id: listId })
              .update({
                data: {
                  tasks: _.push(res._id),
                },
              });
          } else {
            await db
              .collection("taskList")
              .where({ _id: listId })
              .update({
                data: {
                  tasks: _.push(taskId),
                },
              });
          }

          resolve("添加成功");
        } catch (err) {
          console.log("添加任务失败：", err);
          reject(err);
        }
      });
    },

    // 删除整个任务列表
    deleteTaskList({ dispatch }, payload) {
      const db = wx.cloud.database(),
        _ = db.command,
        { listId, taskList, isTeam } = payload;
      return new Promise(async (resolve, reject) => {
        try {
          for (let i = 0; i < taskList.length; i++) {
            const _id = taskList[i];
            await db.collection("task").where({ _id }).remove(); // 删除列表下的所有任务
          }
          await db.collection("taskList").where({ _id: listId }).remove(); // 删除整个列表
          await dispatch(
            "removeTaskToUser",
            { listId, isTeam },
            { root: true }
          );
          await dispatch("getUserInfo", { type: 0 }, { root: true });
          resolve("删除成功");
        } catch (err) {
          console.log("删除列表失败：", err);
          reject(err);
        }
      });
    },
    // 删除列表中的一个任务
    deleteTask({}, payload) {
      const db = wx.cloud.database(),
        _ = db.command,
        { listId, taskId } = payload;
      console.log("查看删除的任务：", listId, taskId);
      return new Promise(async (resolve, reject) => {
        try {
          await db
            .collection("taskList")
            .where({ _id: listId })
            .update({
              data: {
                tasks: _.pull(taskId),
              },
            });
          await db.collection("task").where({ _id: taskId }).remove();
          resolve("删除任务成功");
        } catch (err) {
          console.log("删除任务失败：", err);
          reject(err);
        }
      });
    },

    // 修改任务详情
    updateTaskDetail({}, taskContent) {
      const db = wx.cloud.database(),
        _id = taskContent._id;
      delete taskContent._openid; // 不允许含有_openid字段
      delete taskContent._id; // 不允许含有_id字段
      return new Promise(async (resolve, reject) => {
        try {
          await db
            .collection("task")
            .where({ _id })
            .update({
              data: { ...taskContent },
            });
          resolve("修改任务成功");
        } catch (err) {
          console.log("修改任务失败：", err);
          reject(err);
        }
      });
    },

    // 修改任务状态（判断是否过期）
    changeTaskStatus({}, taskId) {
      const db = wx.cloud.database();
      return new Promise(async (resolve, reject) => {
        try {
          await db
            .collection("task")
            .where({ _id: taskId })
            .update({
              data: {
                isTime: true,
              },
            });
          resolve("修改状态成功");
        } catch (err) {
          console.log("修改状态失败：", err);
          reject(err);
        }
      });
    },

    // 上传富文本中的图片至云存储
    uploadTaskEditorImage({ dispatch }, fileList) {
      if (!fileList.length) {
        resolve("无需要上传的图片");
      }
      return new Promise(async (resolve, reject) => {
        try {
          const uploadFileTasks = fileList.map((file) => {
            return dispatch("uploadContentImage", file);
          });
          try {
            const res = await Promise.all(uploadFileTasks);
            console.log("全部上传成功：", res);
            resolve(res);
          } catch (err) {
            console.log("上传有错误：", err);
            reject(err);
          }
        } catch (err) {
          console.log("富文本图片上传失败：", err);
          reject(err);
        }
      });
    },

    // 上传单张富文本图片
    uploadContentImage({}, file) {
      const { fileName, filePath } = file;
      return new Promise(async (resolve, reject) => {
        try {
          const res = await wx.cloud.uploadFile({
            cloudPath: `editorImage/${fileName}`,
            filePath,
          });
          console.log("上传图片：", res);
          resolve(res);
        } catch (err) {
          reject(err);
        }
      });
    },
  },
};
